package com.ruoyi.cems.service.impl;

import com.ruoyi.base.domain.BaseEmerTeList;
import com.ruoyi.base.domain.BaseEmerTeTemp;
import com.ruoyi.base.service.IBaseEmerTeListService;
import com.ruoyi.base.service.IBaseEmerTeTempService;
import com.ruoyi.cems.domain.*;
import com.ruoyi.cems.domain.dto.BmsEmergencyVariableControlDTO;
import com.ruoyi.cems.mapper.BmsEVCContactMapper;
import com.ruoyi.cems.mapper.BmsEmergencyVariableControlMapper;
import com.ruoyi.cems.mapper.BmsEvcAlternateAirportMapper;
import com.ruoyi.cems.mapper.BmsEvcBelongOfficeContactMapper;
import com.ruoyi.cems.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 变量控制;Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-06-24
 */
@Slf4j
@Service
public class BmsEmergencyVariableControlServiceImpl implements IBmsEmergencyVariableControlService 
{
    @Autowired
    private BmsEmergencyVariableControlMapper bmsEmergencyVariableControlMapper;
    @Autowired
    private BmsEVCContactMapper bmsEVCContactMapper;
    @Autowired
    private BmsEvcAlternateAirportMapper bmsEvcAlternateAirportMapper;
    @Autowired
    private BmsEvcBelongOfficeContactMapper bmsEvcBelongOfficeContactMapper;
    @Autowired
    private IBaseEmerTeListService baseEmerTeListService;
    @Autowired
    private IBaseEmerTeTempService baseEmerTeTempService;
    @Autowired
    private IBmsWorkChecklistsDetailService workChecklistsDetailService;
    @Autowired
    private IBmsWorkChecklistsService bmsWorkChecklistsService;
    @Autowired
    private IBmsUserMessageService bmsUserMessageService;
    @Autowired
    private ILanXinService iLanXinService;

    @Value("${subscriber.messageVc}")
    private String messageVc;


    /**
     * 查询变量控制;
     *
     * @param ID 变量控制;主键
     * @return 变量控制;
     */
    @Override
    public BmsEmergencyVariableControl selectBmsEmergencyVariableControlByID(String ID)
    {
        return bmsEmergencyVariableControlMapper.selectBmsEmergencyVariableControlByID(ID);
    }
    /**
     * 查询变量控制;
     *
     * @param taskNo 变量控制;主键
     * @return 变量控制;
     */
    @Override
    public BmsEmergencyVariableControl selectBmsEmergencyVariableControlByTaskNo(String taskNo)
    {
        return bmsEmergencyVariableControlMapper.selectBmsEmergencyVariableControlByTaskNo(taskNo);
    }

    /**
     * 查询变量控制;列表
     *
     * @param bevcDto 变量控制;
     * @return 变量控制;
     */
    @Override
    public List<BmsEmergencyVariableControl> selectBmsEmergencyVariableControlList(BmsEmergencyVariableControlDTO bevcDto)
    {
        return bmsEmergencyVariableControlMapper.selectBmsEmergencyVariableControlList(bevcDto);
    }

    /**
     * 新增变量控制;
     *
     * @param bmsEmergencyVariableControl 变量控制;
     * @return 结果
     */
    @Override
    public int insertBmsEmergencyVariableControl(BmsEmergencyVariableControl bmsEmergencyVariableControl)
    {
        //新增变量控制表
        int result = bmsEmergencyVariableControlMapper.insertBmsEmergencyVariableControl(bmsEmergencyVariableControl);
        //新增变量控制联络表
        List<BmsEVCContact>bmsEVCContacts = bmsEmergencyVariableControl.getEvcContacts();
        if(Objects.nonNull(bmsEVCContacts) && !bmsEVCContacts.isEmpty()){
            bmsEVCContacts.forEach(bmsEVCContact -> {
                bmsEVCContact.setID(UUID.randomUUID().toString().replace("-", ""));
                bmsEVCContact.setParentId(bmsEmergencyVariableControl.getID());
                bmsEVCContact.setCreatedTime(new Date());
                bmsEVCContact.setCreatedBy(bmsEmergencyVariableControl.getCreatedBy());
                bmsEVCContact.setStatus("Enabled");
                bmsEVCContactMapper.insertBmsEVCContact(bmsEVCContact);
            });
        }
        //新增备降机场联络表
        List<BmsEvcAlternateAirport>bmsEvcAlternateAirports = bmsEmergencyVariableControl.getEvcAlternateAirports();
        if(Objects.nonNull(bmsEvcAlternateAirports) && !bmsEvcAlternateAirports.isEmpty()){
            bmsEvcAlternateAirports.forEach(bmsEvcAlternateAirport -> {
                bmsEvcAlternateAirport.setID(UUID.randomUUID().toString().replace("-", ""));
                bmsEvcAlternateAirport.setVcId(bmsEmergencyVariableControl.getID());
                bmsEvcAlternateAirport.setCreatedTime(new Date());
                bmsEvcAlternateAirportMapper.insertBmsEvcAlternateAirport(bmsEvcAlternateAirport);
            });
        }
        //新增属地应急办联络表
        List<BmsEvcBelongOfficeContact>bmsEvcBelongOfficeContacts = bmsEmergencyVariableControl.getEvcBelongOfficeContacts();
        if(Objects.nonNull(bmsEvcBelongOfficeContacts) && !bmsEvcBelongOfficeContacts.isEmpty()){
            bmsEvcBelongOfficeContacts.forEach(bmsEvcBelongOfficeContact -> {
                bmsEvcBelongOfficeContact.setBelongId(bmsEvcBelongOfficeContact.getID());
                bmsEvcBelongOfficeContact.setID(UUID.randomUUID().toString().replace("-", ""));
                bmsEvcBelongOfficeContact.setVcId(bmsEmergencyVariableControl.getID());
                bmsEvcBelongOfficeContact.setCreatedTime(new Date());
                bmsEvcBelongOfficeContactMapper.insertBmsEvcBelongOfficeContact(bmsEvcBelongOfficeContact);
            });
        }
        return result;
    }

    /**
     * 修改变量控制;
     *
     * @param bmsEmergencyVariableControl 变量控制;
     * @return 结果
     */
    @Override
    public int updateBmsEmergencyVariableControl(BmsEmergencyVariableControl bmsEmergencyVariableControl)
    {
        int result = bmsEmergencyVariableControlMapper.updateBmsEmergencyVariableControl(bmsEmergencyVariableControl);
        //更新变量控制联络表
        //1.全部移除
        bmsEVCContactMapper.deleteBmsEVCContactByParentID(bmsEmergencyVariableControl.getID());
        //2.新增数据
        List<BmsEVCContact>bmsEVCContacts = bmsEmergencyVariableControl.getEvcContacts();
        if(Objects.nonNull(bmsEVCContacts) && !bmsEVCContacts.isEmpty()){
            bmsEVCContacts.forEach(bmsEVCContact -> {
                bmsEVCContact.setID(UUID.randomUUID().toString().replace("-", ""));
                bmsEVCContact.setParentId(bmsEmergencyVariableControl.getID());
                bmsEVCContact.setCreatedTime(new Date());
                bmsEVCContact.setCreatedBy(bmsEmergencyVariableControl.getUpdatedBy());
                bmsEVCContact.setUpdatedTime(new Date());
                bmsEVCContact.setUpdatedBy(bmsEmergencyVariableControl.getUpdatedBy());
                bmsEVCContactMapper.insertBmsEVCContact(bmsEVCContact);
            });
        }
        //更新备降机场联络表
        bmsEvcAlternateAirportMapper.deleteBmsEvcAlternateAirportByVcID(bmsEmergencyVariableControl.getID());
        List<BmsEvcAlternateAirport>bmsEvcAlternateAirports = bmsEmergencyVariableControl.getEvcAlternateAirports();
        if(Objects.nonNull(bmsEvcAlternateAirports) && !bmsEvcAlternateAirports.isEmpty()){
            bmsEvcAlternateAirports.forEach(bmsEvcAlternateAirport -> {
                bmsEvcAlternateAirport.setID(UUID.randomUUID().toString().replace("-", ""));
                bmsEvcAlternateAirport.setVcId(bmsEmergencyVariableControl.getID());
                bmsEvcAlternateAirport.setCreatedTime(new Date());
                bmsEvcAlternateAirport.setCreatedBy(bmsEmergencyVariableControl.getUpdatedBy());
                bmsEvcAlternateAirport.setUpdatedTime(new Date());
                bmsEvcAlternateAirport.setUpdatedBy(bmsEmergencyVariableControl.getUpdatedBy());
                bmsEvcAlternateAirportMapper.insertBmsEvcAlternateAirport(bmsEvcAlternateAirport);
            });
        }
        //更新属地应急办联络表
        bmsEvcBelongOfficeContactMapper.deleteBmsEvcBelongOfficeContactByVcID(bmsEmergencyVariableControl.getID());
        List<BmsEvcBelongOfficeContact>bmsEvcBelongOfficeContacts = bmsEmergencyVariableControl.getEvcBelongOfficeContacts();
        if(Objects.nonNull(bmsEvcBelongOfficeContacts) && !bmsEvcBelongOfficeContacts.isEmpty()){
            bmsEvcBelongOfficeContacts.forEach(bmsEvcBelongOfficeContact -> {
                if(bmsEvcBelongOfficeContact.getBelongId() == null){
                    bmsEvcBelongOfficeContact.setBelongId(bmsEvcBelongOfficeContact.getID());
                }
                bmsEvcBelongOfficeContact.setID(UUID.randomUUID().toString().replace("-", ""));
                bmsEvcBelongOfficeContact.setVcId(bmsEmergencyVariableControl.getID());
                bmsEvcBelongOfficeContact.setCreatedTime(new Date());
                bmsEvcBelongOfficeContact.setCreatedBy(bmsEmergencyVariableControl.getUpdatedBy());
                bmsEvcBelongOfficeContact.setUpdatedTime(new Date());
                bmsEvcBelongOfficeContact.setUpdatedBy(bmsEmergencyVariableControl.getUpdatedBy());
                bmsEvcBelongOfficeContactMapper.insertBmsEvcBelongOfficeContact(bmsEvcBelongOfficeContact);
            });
        }
        return result;
    }

    /**
     * 批量删除变量控制;
     *
     * @param IDs 需要删除的变量控制;主键
     * @return 结果
     */
    @Override
    public int deleteBmsEmergencyVariableControlByIDs(String[] IDs)
    {
        if (Objects.nonNull(IDs) && IDs.length > 0){
            Arrays.stream(IDs).forEach(ID -> {
                //删除变量控制联络表
                bmsEVCContactMapper.deleteBmsEVCContactByParentID(ID);
                //删除备降机场联络表
                bmsEvcAlternateAirportMapper.deleteBmsEvcAlternateAirportByVcID(ID);
                //删除属地应急办联络表
                bmsEvcBelongOfficeContactMapper.deleteBmsEvcBelongOfficeContactByVcID(ID);
            });
        }
        return bmsEmergencyVariableControlMapper.deleteBmsEmergencyVariableControlByIDs(IDs);
    }

    /**
     * 删除变量控制;信息
     *
     * @param ID 变量控制;主键
     * @return 结果
     */
    @Override
    public int deleteBmsEmergencyVariableControlByID(String ID)
    {
        if(Objects.nonNull(ID)){
            //删除变量控制联络表
            bmsEVCContactMapper.deleteBmsEVCContactByParentID(ID);
            //删除备降机场联络表
            bmsEvcAlternateAirportMapper.deleteBmsEvcAlternateAirportByVcID(ID);
            //删除属地应急办联络表
            bmsEvcBelongOfficeContactMapper.deleteBmsEvcBelongOfficeContactByVcID(ID);
        }
        return bmsEmergencyVariableControlMapper.deleteBmsEmergencyVariableControlByID(ID);
    }

    @Override
    public int start(BmsEmergencyVariableControl bmsEmergencyVariableControl,String userId) {
        bmsEmergencyVariableControl.setStatus("2");//启用
        bmsEmergencyVariableControl.setFillDate(new Date());
        userMessage(bmsEmergencyVariableControl,userId);//生成变量控制表用户消息

        //发布变量控制表，同时将检查单推送给指挥员/B1总指挥/B2航管监控
        BmsEVCContact bevcc = new BmsEVCContact();
        bevcc.setParentId(bmsEmergencyVariableControl.getID());
        bevcc.setFlag(true);
        List<BmsEVCContact> list = bmsEVCContactMapper.getEVCContactListByparentId(bevcc);
        if(Objects.nonNull(list) && !list.isEmpty()) {
            list.forEach(bmsEVCContact -> {
                //生成检查单
                BmsWorkChecklists bmsWorkChecklists = new BmsWorkChecklists();
                bmsWorkChecklists.setID(UUID.randomUUID().toString().replace("-",""));
                bmsWorkChecklists.setEnId("");
                bmsWorkChecklists.setCreatedBy(userId);
                bmsWorkChecklists.setCreatedTime(new Date());
                bmsWorkChecklists.setLevel("");
                bmsWorkChecklists.setTaskNo(bmsEmergencyVariableControl.getTaskNo());
                bmsWorkChecklists.setCheckPeople(bmsEVCContact.getName());
                bmsWorkChecklists.setCheckPeopleId(bmsEVCContact.getUserId());
                bmsWorkChecklists.setPosition(bmsEVCContact.getPosition());
                bmsWorkChecklists.setBelong(bmsEVCContact.getRole());
                bmsWorkChecklists.setNoticeStatus(true);
                bmsWorkChecklists.setJobNumber(bmsEVCContact.getJobNumber());
                bmsWorkChecklists.setPhone(bmsEVCContact.getTel());
                bmsWorkChecklists.setStatus("新建");

                //获取检查单信息
                BaseEmerTeList baseEmerTeList = baseEmerTeListService.selectBaseEmerTeListByViewAndPosition("",bmsEVCContact.getPosition(),bmsEmergencyVariableControl.getUnitCode());
                if (baseEmerTeList != null){
                    bmsWorkChecklists.setCheckName(bmsEmergencyVariableControl.getTaskName());
                    bmsWorkChecklists.setView(baseEmerTeList.getView());
                    BaseEmerTeTemp bttemp= new BaseEmerTeTemp();
                    bttemp.setEmerTeId(baseEmerTeList.getID());
                    //生成检查单明细
                    List<BaseEmerTeTemp> baseEmerTeTemps = baseEmerTeTempService.selectBaseEmerTeTempList(bttemp);
                    if (baseEmerTeTemps != null && !baseEmerTeTemps.isEmpty()){
                        for (BaseEmerTeTemp baseEmerTeTemp : baseEmerTeTemps) {
                            BmsWorkChecklistsDetail bmsWorkChecklistsDetail = new BmsWorkChecklistsDetail();
                            bmsWorkChecklistsDetail.setID(UUID.randomUUID().toString().replace("-",""));
                            bmsWorkChecklistsDetail.setCheckId(bmsWorkChecklists.getID());
                            bmsWorkChecklistsDetail.setView("");
                            bmsWorkChecklistsDetail.setInput(baseEmerTeTemp.getInput());
                            bmsWorkChecklistsDetail.setOutput(baseEmerTeTemp.getOutput());
                            bmsWorkChecklistsDetail.setResponseStage(baseEmerTeTemp.getResponseStage());
                            bmsWorkChecklistsDetail.setNum(baseEmerTeTemp.getNum());
                            bmsWorkChecklistsDetail.setCompletion("未完成");
                            bmsWorkChecklistsDetail.setCreatedBy(userId);
                            bmsWorkChecklistsDetail.setCreatedTime(new Date());
                            //新增检查单明细
                            workChecklistsDetailService.insertBmsWorkChecklistsDetail(bmsWorkChecklistsDetail);
                        }
                    }
                }
                //新增检查单
                bmsWorkChecklistsService.insertBmsWorkChecklists(bmsWorkChecklists);
            });
        }

        return bmsEmergencyVariableControlMapper.updateBmsEmergencyVariableControl(bmsEmergencyVariableControl);
    }

    private void userMessage(BmsEmergencyVariableControl bmsEmergencyVariableControl,String userId){
//        BmsEVCContact bevcc = new BmsEVCContact();
//        bevcc.setParentId(bmsEmergencyVariableControl.getID());
//        bevcc.setType("command");
        List<BmsEVCContact> list = bmsEVCContactMapper.selectBmsEVCContactListByparentId(bmsEmergencyVariableControl.getID(),"command");
        Set<String> processedUsers = new HashSet<>();
        List<String> userIdList = new ArrayList<>();
        if (Objects.nonNull(list) && !list.isEmpty()) {
            list.forEach(bmsEVCContact -> {
                // 检查是否已经处理过该用户
                if (!processedUsers.contains(bmsEVCContact.getUserId())) {
                    // 生成系统消息
                    BmsUserMessage bmsUserMessage = new BmsUserMessage();
                    bmsUserMessage.setID(UUID.randomUUID().toString().replace("-", ""));
                    bmsUserMessage.setVcId(bmsEmergencyVariableControl.getID());
                    bmsUserMessage.setCreatedBy(userId);
                    bmsUserMessage.setCreatedTime(new Date());
                    bmsUserMessage.setUserId(bmsEVCContact.getUserId());
                    bmsUserMessage.setType(1);
                    bmsUserMessage.setMessage(messageVc);
                    bmsUserMessageService.insertBmsUserMessage(bmsUserMessage);

                    // 添加到已处理集合中
                    processedUsers.add(bmsEVCContact.getUserId());
                    //添加蓝信发送信息手机号
                    userIdList.add(bmsEVCContact.getPhonenumber());
                }
            });
        }


        //发送蓝信信息
        if(userIdList != null && !userIdList.isEmpty()) {
//            iLanXinService.sendTextMessage(userIdList, "您有一张应急变量控制表单，请登录蓝信“应急管理系统”查看");
            iLanXinService.sendLinkCardMessage(userIdList, "应急变量控制表","https://comac-yjgl.e.lanxin.cn");
        }
    }


    @Override
    public int copy(String id ,String userId) {
        BmsEmergencyVariableControl bevcc = bmsEmergencyVariableControlMapper.selectBmsEmergencyVariableControlByID(id);
        if (bevcc != null){
            String  newId = UUID.randomUUID().toString().replace("-", "");
            bevcc.setTaskName("复制"+bevcc.getTaskName());
            bevcc.setTaskNo("复制"+bevcc.getTaskNo());
            bevcc.setNo("复制"+bevcc.getNo());
            bevcc.setEocAddress(bevcc.getEocAddress());
            bevcc.setID(newId);
            bevcc.setStatus("1");
            bevcc.setCreatedBy(userId);
            bevcc.setCreatedTime(new Date());
            int result =  bmsEmergencyVariableControlMapper.insertBmsEmergencyVariableControl(bevcc);

            //获取原变量控制联络表
            List<BmsEVCContact> evccList = bmsEVCContactMapper.selectBmsEVCContactListByparentId(id,null);
            //获取原备降机场联络表
            List<BmsEvcAlternateAirport> beaaList = bmsEvcAlternateAirportMapper.selectBmsEvcAlternateAirportListByVcId(id);
            //获取原属地应急办联络表
            List<BmsEvcBelongOfficeContact> bebocList =  bmsEvcBelongOfficeContactMapper.selectBmsEvcBelongOfficeContactListByVcId(id);

            //复制变量控制联络表
            if(Objects.nonNull(evccList) && !evccList.isEmpty()){
                evccList.forEach(bmsEVCContact -> {
                    bmsEVCContact.setID(UUID.randomUUID().toString().replace("-", ""));
                    bmsEVCContact.setParentId(newId);
                    bmsEVCContact.setCreatedBy(userId);
                    bmsEVCContact.setCreatedTime(new Date());
                    bmsEVCContactMapper.insertBmsEVCContact(bmsEVCContact);
                });
            }
            //复制备降机场联络表
            if(Objects.nonNull(beaaList) && !beaaList.isEmpty()){
                beaaList.forEach(bmsEvcAlternateAirport -> {
                    bmsEvcAlternateAirport.setID(UUID.randomUUID().toString().replace("-", ""));
                    bmsEvcAlternateAirport.setVcId(newId);
                    bmsEvcAlternateAirport.setCreatedBy(userId);
                    bmsEvcAlternateAirport.setCreatedTime(new Date());
                    bmsEvcAlternateAirportMapper.insertBmsEvcAlternateAirport(bmsEvcAlternateAirport);
                });
            }
            //复制属地应急办联络表
            if(Objects.nonNull(bebocList) && !bebocList.isEmpty()){
                bebocList.forEach(bmsEvcBelongOfficeContact -> {
                    bmsEvcBelongOfficeContact.setID(UUID.randomUUID().toString().replace("-", ""));
                    bmsEvcBelongOfficeContact.setVcId(newId);
                    bmsEvcBelongOfficeContact.setCreatedBy(userId);
                    bmsEvcBelongOfficeContact.setCreatedTime(new Date());
                    bmsEvcBelongOfficeContactMapper.insertBmsEvcBelongOfficeContact(bmsEvcBelongOfficeContact);
                });
            }
            return result;

        }
        return 0;
    }

    /**
     * 查询业务数据数量
     *
     * @param start_time
     * @param end_time
     * @return
     */
    @Override
    public int selectBmsEmergencyVariableControlCount(String start_time, String end_time) {
        int data_num = bmsEmergencyVariableControlMapper.selectBmsEmergencyVariableControlCount(start_time, end_time);
        return data_num;
    }

    @Override
    public int updateBmsEmergencyVariableStatus() {
        return bmsEmergencyVariableControlMapper.updateBmsEmergencyVariableStatus();
    }


}
